from distutils.errors import DistutilsError
import os
import sys
import time

from dbmigrate.command import BaseMigrationCommand
from dbmigrate.migration import get_data_source, MigrationEngine

class dbmigrate(BaseMigrationCommand):

    description = "perform migrations"  
    command_consumes_arguments = True    

    user_options = [
                    ('package=', 'p', "the package containing the migration scripts"
                     "(default: migrations)"),
                    ('revision=', 'r', "the desired revision"),
                    ('scheme=', 's', "database migration scheme"),
                    ('admin-user=', None, "the database administration user"),
                    ('admin-pw=', None, "the database administration password"),
                    ('user=', None, "the new database user"),
                    ('host=', 'h', "the database server"),
                    ('port=', None, "the database server port"),
                    ('db=', 'd', "the database name"),
                    ('pw=', None, "the database password"),
                    ('filename=', 'f', "the database filename"),
                    ('socket=', None, "the unix domain socket"),
                    ]
    
    def initialize_options(self):
        BaseMigrationCommand.initialize_options(self)
        self.package = None
        self.revision = None
        self.scheme = None
        self.admin_user = None
        self.admin_pw = None
        self.user = None
        self.pw = None
        self.host = None
        self.port = None
        self.db = None
        self.filename = None
        self.socket = None
        self.args = None
        
    def finalize_options(self):
        BaseMigrationCommand.finalize_options(self)
        if self.revision:
            self.revision = int(self.revision)
#        self.assert_field_defined('scheme', "the database scheme must be defined")
#        self.assert_has_required_options(get_data_source(self.scheme))
        if self.args:
            self.package = self.args
    
    def run(self):
        migration = MigrationEngine(self.package, self.get_data_source(), self)
        migration.migrate_database()
    
    def get_data_source(self):
        data_source = get_data_source(self.scheme)
        return data_source.from_command(self)
